package org.glorylight.hacks.social.service;

import java.util.UUID;

import org.glorylight.hacks.social.data.UserData;
import org.glorylight.hacks.social.model.ScrapBook;
import org.glorylight.hacks.social.model.ScrapBookVotes;
import org.glorylight.hacks.social.model.Voter;
import org.glorylight.hacks.social.util.UUIDHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(readOnly = true)
public class VoteService extends BaseService {
	
	private static final Logger log = LoggerFactory.getLogger(VoteService.class);
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private ScrapBookService scrapBookService;
	
	@Transactional(readOnly = false)
	public void vote(UUID scrapId, String emailId) throws Exception {
		ScrapBook scrapBook = em.find(ScrapBook.class, scrapId);
		UserData userData = userService.find(emailId);
		Voter voter = new Voter(userData.getFirstName(), userData.getLastName(), UUIDHelper.stringToUUID(userData.getUserId()));
		scrapBook.getVoters().add(new ScrapBookVotes(UUID.randomUUID(), scrapBook, voter));
		log.debug("trying to save new voter({},{},{}) for scrapbook {}", new Object[]{userData.getFirstName(), userData.getLastName(), userData.getUserId(), UUIDHelper.uuidToString(scrapId)});
		add(scrapBook);
	}
	
	@Transactional(readOnly = false)
	public void unvote(UUID scrapId, String emailId) throws Exception {
		ScrapBook scrapBook = em.find(ScrapBook.class, scrapId);
		UserData userData = userService.find(emailId);
		Voter voter = new Voter(userData.getFirstName(), userData.getLastName(), UUIDHelper.stringToUUID(userData.getUserId()));
		scrapBook.getVoters().remove(new ScrapBookVotes(UUID.randomUUID(), scrapBook, voter));
		log.debug("trying to remove existing voter({},{},{}) for scrapbook {}", new Object[]{userData.getFirstName(), userData.getLastName(), userData.getUserId(), UUIDHelper.uuidToString(scrapId)});
		update(scrapBook);
	}

}
